//
//  XLRefreshControl.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/9.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit

//定义刷新控件的三种枚举状态
enum XLRefreshType: String {
    case normal = "normal"
    case pulling = "pulling"
    case refreshing = "refreshing"
}

private let XLRefreshControlH: CGFloat = 50

class XLRefreshControl: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //记录父控件
    weak var scrollView: UIScrollView?
    //刷新完毕调用
    func endRefreshing() {
        //将刷新状态改成normal
        self.refreshState = .normal
       
    }
    //记录默认状态
    var refreshState: XLRefreshType = .normal {
        didSet {
            switch refreshState {
            case .pulling:
                // 调转箭头
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                // 更改文字 --> 松开起
                self.messageLabel.text = "松开起飞"
            case .normal:
                // 进入到默认状态应该将菊花转停止掉
                indicatorView.stopAnimating()
                // 箭头显示出来
                arrowIcon.isHidden = false
                //箭头恢复到原始位置
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                self.messageLabel.text = "等待起飞"
                //判断如果是刷新状态, 才执行下面的代码
                //把inset移回去
                if oldValue == .refreshing{
                    UIView.animate(withDuration: 0.25) {
                        var inset = self.scrollView!.contentInset
                        inset.top -= XLRefreshControlH
                        self.scrollView!.contentInset = inset
                        self.scrollView?.setContentOffset(CGPoint(x: 0, y: -inset.top), animated: false)

                    }
                }
                
            case .refreshing:
                // 把箭头隐藏，显示菊花转
                arrowIcon.isHidden = true
                indicatorView.startAnimating()
                self.messageLabel.text = "正在起飞"
                
                UIView.animate(withDuration: 0.25, animations: {
                    // 如果让其在转的时候停止在界面的顶端
                    // 为tableView顶部增加多余的滑动距离
                    var inset = self.scrollView!.contentInset
                    inset.top += XLRefreshControlH
                    self.scrollView!.contentInset = inset
                })
                //发送事件, 其实就是调用addTarget中的方法
                sendActions(for: UIControlEvents.valueChanged)
            }
        }
    }
    
    func setupUI() {
        backgroundColor = UIColor.green
        
        frame.size = CGSize(width: HMScreenW, height: XLRefreshControlH)
        frame.origin.y = -XLRefreshControlH
        
        //添加到视图
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        //布局
        arrowIcon.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowIcon.snp_trailing)
            make.centerY.equalTo(arrowIcon)
        }
        
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        if newSuperview is UIScrollView {
            self.scrollView = newSuperview as? UIScrollView
            //给tableView添加观察者
            //参数说明: keyPath: 要观察的属性,  options: 发生变化前的旧值&发生变化后的新值
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new, .old], context: nil)
        }
    }
    //xlrefreshControl在该方法中收到tableView的contentOffSet变化的消息
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //print(self.scrollView?.contentOffset)
        let contentInsetTop = self.scrollView!.contentInset.top
        // 如果小于这个值，就代表当前控件已经完全显示出来了
        let conditionValue: CGFloat = -contentInsetTop - XLRefreshControlH

        
        if self.scrollView!.isDragging {
            //在拖动
            if self.refreshState == .normal && self.scrollView!.contentOffset.y <= conditionValue {
                //进入刷新状态
                self.refreshState = .pulling
            }else if self.refreshState == .pulling && self.scrollView!.contentOffset.y > conditionValue{
                //又回到默认状态
                self.refreshState = .normal
            }
        }else{
            //没有拖动, 即松手
            if self.refreshState == .pulling{
                self.refreshState = .refreshing
            }
        }

    
    }
    //一定要移除观察者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    

    //懒加载
    lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGray, fontSize: 13)
        label.text = "等待起飞"
        return label
    }()
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView()
        indicator.color = .black
        return indicator
    }()

}
